#define _CRT_SECURE_NO_WARNINGS 1


#include <vector>
using namespace std;

 // Definition for a binary tree node.
  struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode *right;
     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  };
class Solution {
public:
    TreeNode* _build(vector<int>& preorder, vector<int>& inorder, int& i, int begin, int end)
    {
        if (begin > end)
            return nullptr;
        if (i > preorder.size() - 1)
            return nullptr;
        int ri = begin;
        while (inorder[ri] != preorder[i] && ri <= end)
        {
            ++ri;
        }
        if (ri > end)
            return nullptr;
        int lbegin = 0, lend = ri - 1;
        int rbegin = ri + 1, rend = end;
        TreeNode* proot = new TreeNode(preorder[i++]);
        proot->left = _build(preorder, inorder, i, lbegin, lend);
        proot->right = _build(preorder, inorder, i, rbegin, rend);
        return proot;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int i = 0;
        return _build(preorder, inorder, i, 0, preorder.size() - 1);
    }
};